package reports.directors;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.Set;

import coreModel.*;
import reports.builders.IBuilder;

public class RemovedItemsReport implements IDirector {

	
	private Date sinceDate;
	private SimpleDateFormat dateFormater;
	private ArrayList<String> headers;
	private Set<Product> products;
	
	@Override
	public void build(IBuilder builder)
	{
		builder.addTitle("Items Removed Since "+dateFormater.format(sinceDate));
		builder.startTable(headers.size());
		builder.addTableHeader(headers);
		//added for bug fix
		ArrayList<Product> newArray = new ArrayList<Product>();
		newArray.addAll(products);
		Collections.sort(newArray, new ProductComparator());
		
		for(Product product : newArray)
		{
			Collection<String> tmp = buildArray(product);
			if(!tmp.isEmpty())
				builder.addRow(tmp);
		}
		builder.endTable();
		builder.saveToFile();
		

	}
	private Collection<String> buildArray(Product product)
	{
		Collection<Item> items=HIT.getInstance().getItemHistory().getRemovedItemsByProduct(product);
		ArrayList<Item> actualItems=new ArrayList<Item>();
		for(Item item : items)
		{
			if(item.getExitTime().after(sinceDate))
			{
				actualItems.add(item);
			}
		}
		ArrayList<String> tmp = new ArrayList<String>();
		if(!actualItems.isEmpty())
		{
			tmp.add(product.getDescription());
			tmp.add(product.getSupply().toString());
			tmp.add(product.getBarcode().toString());
			tmp.add(Integer.toString(actualItems.size()));
			if(HIT.getInstance().getItemManager().getAllItemsOfProduct(product)!=null)
					tmp.add(Integer.toString(HIT.getInstance().getItemManager().
							getAllItemsOfProduct(product).size()));
			
			
		}
		return tmp;
	}
	public RemovedItemsReport(Date sinceDate)
	{
		
		
		this.sinceDate= sinceDate;
		dateFormater= new SimpleDateFormat("MM/dd/yyyy hh:mm a");
		products= HIT.getInstance().getItemHistory().getAllProducts();
		headers=new ArrayList<String>();
		
		headers.add("Description");
		headers.add("Size");
		headers.add("Product Barcode");
		headers.add("Removed");
		headers.add("Current Supply");
	}
	
	private class ProductComparator implements Comparator<Product>
	{

		@Override
		public int compare(Product o1, Product o2)
		{
			if(o1.getDescription().equals(o2.getDescription()))
			{
				return o1.getCreationDate().compareTo(o2.getCreationDate());
			}
			else
			{
				return o1.getDescription().compareTo(o2.getDescription());
			}
		}
		
	}

	

}
